package com.android.allwinner.newaw360.storage;



import com.android.allwinner.newaw360.media.MediaFileInfo;
import com.android.allwinner.newaw360.utils.LogUtil;
import com.android.allwinner.newaw360.utils.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xiashaojun on 16-12-15.
 */

public class AW360StorageManager {
    private static final String TAG = AW360StorageManager.class.getSimpleName();

    public List<MediaFileInfo> getVideoFiles(String path) {
        List<MediaFileInfo> videoList = new ArrayList<MediaFileInfo>();
        File dir = new File(path);
        File[] files = dir.listFiles();
        if (files == null) {
            LogUtil.d(TAG,"addVideoListFromDir: mfile.listFiles() returns null!");
            return null;
        }

        String[] filePaths = new String[files.length];
        for (int i = 0; i < files.length; i++) {
            filePaths[i] = files[i].getAbsolutePath();
        }
        filePaths = StringUtils.sortStrings(filePaths);

        MediaFileInfo fileInfo = null;

        for (int i = 0; i < filePaths.length; i++) {
            File file = files[i];
            if (checkIsVideoFile(filePaths[i])) {
                fileInfo = getFileInfoFromPath(filePaths[i]);
                if (fileInfo != null) {
                    videoList.add(fileInfo);
                }
            } else {
                LogUtil.d(TAG, "addVideoListFromDir: Deleting non-video "
                        + file.getAbsolutePath());
                file.delete();
            }
        }
        return videoList;
    }


    private boolean checkIsVideoFile(String fName) {
        boolean isVideoFile = false;

        // 获取扩展名
        String FileEnd = fName.substring(fName.lastIndexOf(".") + 1,
                fName.length()).toLowerCase();
        if (FileEnd.equals("mp4")) { // || FileEnd.equals("tmp")) {
            isVideoFile = true;
        } else {
            isVideoFile = false;
        }
        return isVideoFile;
    }

    private MediaFileInfo getFileInfoFromPath(String path) {
        MediaFileInfo fileInfo = new MediaFileInfo();
        File file = new File(path);
        fileInfo.setPath(path);
        String fileName = file.getName();
        fileInfo.setName(fileName);
        String timedate[] = fileName.split("_");

        String strData = timedate[1].substring(0);
        String strTime = timedate[2].substring(0, 6);

        StringBuilder sb1 = new StringBuilder(strData);
        StringBuilder sb2 = new StringBuilder(strTime);
        sb1.insert(4, "-");
        sb1.insert(7, "-");
        sb2.insert(2, ":");
        sb2.insert(5, ":");

        fileInfo.setDate(sb1.toString());
        fileInfo.setTime(sb2.toString());
        return fileInfo;
    }

}
